package com.yun.zf.system.security.service;

import com.yun.zf.common.admin.domain.LoginUser;
import com.yun.zf.common.admin.domain.SysAgent;
import com.yun.zf.common.admin.domain.SysUser;
import com.yun.zf.common.admin.domain.SysUserPhone;
import com.yun.zf.common.enums.UserStatus;
import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.system.exception.BaseException;
import com.yun.zf.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserPhoneService phoneService;
    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysAgentService agentService;
    @Autowired
    private SysUserAuthService authService;

    //5tgb^YHN
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户账号（手机号码）查询分表关联的userId
        SysUserPhone phone = phoneService.getByIphone(Long.parseLong(username));
        if (StringUtils.isNull(phone)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        //分库分表中通过用户账号，以及用户表的主键UserId获取用户信息
        SysUser user = userService.selectUserByUserName(username, phone.getUserId());
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        // 登录完成查看是否是业务员，如果是业务员，则把城市区划代码， 业务员工号,业务员名称放入token
        SysAgent agent = agentService.getInfoByUserId(user.getUserId());
        if (agent != null) {
            Long cityCode = agent.getCityCode();
            Long provinceCode = agent.getProvinceCode();
            int agentNo = agent.getAgentNo();
            String agentName = agent.getName();
            Long deptId = agent.getDeptId();
            return createLoginUser(user, String.valueOf(cityCode), agentNo, agentName, String.valueOf(provinceCode), deptId);
        } else {
            // 如果非业务员直接进行登录
            return createLoginUser(user, null, -1, null, null, null);

        }

    }

    public UserDetails createLoginUser(SysUser user, String cityCode, int agentNo, String agentName, String provinceCode, Long deptId) {
        LoginUser u = new LoginUser();
        u.setOwnUser(user.getUserName());
        u.setOwnPass(user.getPassword());
        u.setUserId(user.getUserId());
        u.setCityCode(cityCode);
        u.setProvinceCode(provinceCode);
        u.setAgentNo(agentNo);
        u.setAgentName(agentName);
        u.setDeptId(deptId);
        u.setPermissions(permissionService.getMenuPermission(user.getUserId()));
        u.setLoginType("iphone");
        return u;
    }
}
